/*
 * @Description:交互处理，用于功能间通过数据UI交互
 * @Version: 2.0
 * @Autor: wiz
 * @Date: 2023-10-27 13:29:23
 * @LastEditors: swc
 * @LastEditTime: 2025-01-22 14:30:06
 */

import libutils from '@/lib/utils';
import { N_oInteraction, N_oMagicbox } from '@/types';
import { modal } from 'vxe-table';
import { ModalController } from 'vxe-table/types';
import XEUtils from 'xe-utils';
import { I_return, T_return } from './return';

export class T_interaction {
  // 直接使用vxe-modal
  private dialog: ModalController = modal;

  /**
   * @description: 解析一个会话消息，返回oInteraction组件配置
   * @param {N_oInteraction.I_msg} msg
   * @return {*}
   * @author: zss
   * @Date: 2024-11-15 10:28:21
   * @LastEditors: zss
   * @LastEditTime: Do not edit
   */
  public parseMsg(
    msg: N_oInteraction.I_msg
  ): I_return<N_oInteraction.I_conf | N_oInteraction.I_srvCmd> {
    const result = new T_return<N_oInteraction.I_conf>();
    switch (msg?.cmd) {
      case N_oInteraction.V_cmd.DIALOG:
        return this.parseDialog(msg.msgContent as N_oInteraction.I_dialog);
      // break;
      case N_oInteraction.V_cmd.FUN_PANEL:
        return this.parseFunPanel(msg.msgContent as N_oInteraction.I_funPanel);
      // break;
      case N_oInteraction.V_cmd.UNITE_PANEL:
        return this.parseUnitePanel(
          msg.msgContent as N_oInteraction.I_unitePanel
        );
      // break;
      case N_oInteraction.V_cmd.OPEN_FUN:
        return this.parseOpenFun(msg.msgContent as N_oInteraction.I_openFun);
      // break;
      case N_oInteraction.V_cmd.FIELD_EVENT:
        return this.parseFieldEvent(
          msg.msgContent as N_oInteraction.I_fieldEvent
        );
      // break;
      case N_oInteraction.V_cmd.JUMP_TO_FUN: // 打开新的功能页签
        return this.parsejumpToFun(
          msg.msgContent as N_oInteraction.I_jumpToFun
        );
      // break;
      case N_oInteraction.V_cmd.EXECUTE_ACTIONS: // 打开新的功能页签
        return this.parseHandleActions(
          msg.msgContent as N_oInteraction.I_executeActions
        );
      // break;
      case N_oInteraction.V_cmd.SEARCH_FILTER: // 打开新的功能页签
        return this.parseSearchFilter(
          msg.msgContent as N_oInteraction.I_searchFilter
        );
      // break;
      case N_oInteraction.V_cmd.FRONTEND_BEHAVIOR: // 打开新的功能页签
        return this.parseFrontendBehavior(
          msg.msgContent as { [key: string]: N_oInteraction.I_frontendBehavior }
        );
      // break;
      default:
        result.errmsg = '-512,FE,90,Unrecognized commands';
        console.error('-512,FE,90,Unrecognized commands');
    }
    return result;
  }

  // 参数检查 返回错误消息。空则ok
  private dialogParamsChk(mc: N_oInteraction.I_dialog): string {
    let chkVal: boolean = true;
    if (!mc?.workID) {
      return `-118,FE,90,*workID#`;
    }
    if (!mc?.type) {
      return `-118,FE,90,*type#`;
    }
    if (!mc?.status) {
      return `-118,FE,90,*status#`;
    }
    if (!mc?.title) {
      return `-118,FE,90,*title#`;
    }
    if (!mc?.content) {
      return `-118,FE,90,*content#`;
    }
    chkVal = /^(alert|confirm|message)$/.test(mc.type.toString());
    if (!chkVal) {
      return `-118,FE,90,*dialog[type]#`;
    }
    chkVal = /^(info|success|warning|error|loading)$/.test(
      mc.status.toString()
    );
    if (!chkVal) {
      return `-551,FE,90,*dialog[type]#`;
    }
    return ``;
  }

  private parseDialog(
    mc: N_oInteraction.I_dialog
  ): I_return<N_oInteraction.I_conf> {
    const conf: N_oInteraction.I_conf = {
      openCompName: '',
      workID: mc.workID,
      cmd: N_oInteraction.V_cmd.DIALOG,
      compBind: {},
      compConf: {}
      // eventNames: []
    };
    const result = new T_return<N_oInteraction.I_conf>();
    const errMsg = this.dialogParamsChk(mc);
    if (errMsg !== ``) {
      result.errmsg = errMsg;
      return result;
    }
    conf.compBind = {
      value: true,
      // width: '600',
      // height: '400',
      type: mc.type,
      status: mc.status,
      title: mc.title,
      content: mc.content,
      showFooter: true,
      minWidth: 400,
      minHeiht: 169,
      // showHeader: false,
      showTitleOverflow: true
    };
    result.setReturnData('conf', conf);
    return result;
  }

  public funPanelParamsChk(mc: N_oInteraction.I_funPanel): string {
    const chkVal: boolean = true;
    if (!mc?.workID) {
      return `-118,FE,90,*workID#`;
    }
    if (!mc?.group) {
      return `-118,FE,90,*group#`;
    }
    for (const k of Object.keys(mc.group)) {
      for (const gitm of mc.group[k]) {
        if (XEUtils.get(gitm as any, 'form.fields', 'null') !== 'null') {
          if (!Array.isArray(gitm.form.fields)) {
            return `-118,FE,90,*fields#`;
          }
          for (const f of gitm.form.fields) {
            const keys = Object.keys(f);
            if (keys.findIndex(e => e === 'field') === -1) {
              return `-118,FE,90,*fields[i].field#`;
            }
            if (keys.findIndex(e => e === 'type') === -1) {
              return `-118,FE,90,*fields[i].type#`;
            }
          }
        }
        if (
          XEUtils.get(gitm as any, 'table.columns', 'null') !== 'null' &&
          !Array.isArray(gitm.table.columns)
        ) {
          return `-118,FE,90,*columns#`;
        }
      }
    }
    return ``;
  }

  private parseFunPanel(
    mc: N_oInteraction.I_funPanel
  ): I_return<N_oInteraction.I_conf> {
    const conf: N_oInteraction.I_conf = {
      openCompName: '',
      workID: mc.workID,
      cmd: N_oInteraction.V_cmd.FUN_PANEL,
      compBind: {},
      compConf: {}
      // eventNames: []
    };
    const result = new T_return<N_oInteraction.I_conf>();
    const errMsg = this.funPanelParamsChk(mc);
    if (errMsg !== ``) {
      result.errmsg = errMsg;
      return result;
    }
    conf.compBind = {
      value: true, // 显示窗口
      width: mc?.style?.width ?? '600',
      height: mc?.style?.height ?? '400',
      type: 'confirm',
      mask: mc?.style?.mask ?? false,
      // 是否允许窗口边缘拖动调整窗口大小
      resize: mc?.style?.resize ?? true,
      // 标题是否标显示最大化与还原按钮
      showZoom: mc?.style?.showZoom ?? true,
      showClose: mc?.style?.showClose ?? true,
      // status: '',
      title: mc.title,
      showFooter: true,
      minWidth: mc?.style?.minWidth,
      minHeiht: mc?.style?.minHeight,
      // 是否允许按 Esc 键关闭窗口
      escClosable: mc?.style?.escClosable ?? false, // default false
      // showHeader: false,
      showTitleOverflow: true
    };

    conf.compConf = this.getCompConf(mc);
    conf.compConf.initValue = mc?.initValue ?? null;
    result.setReturnData('conf', conf);
    return result;
  }

  private getCompConf(mc: N_oInteraction.I_funPanel): object {
    if (!libutils.noValue(mc.group)) {
      Object.keys(mc.group).forEach(k => {
        mc.group[k].forEach((el, idx) => {
          if (XEUtils.get(el as any, 'form.fields', 'null') !== 'null') {
            // form
            this.getFormConf(mc.group[k][idx].form as N_oInteraction.I_form);
          }
          if (XEUtils.get(el as any, 'table.columns', 'null') !== 'null') {
            this.getTableConf(mc.group[k][idx].table as N_oInteraction.I_table);
          }
        });
      });
    }
    return mc;
  }
  // private getInitValue(mc: N_oInteraction.I_funPanel):object{

  // }

  public unitePanelParamsChk(mc: N_oInteraction.I_unitePanel): string {
    const chkVal: boolean = true;
    if (!mc?.workID) {
      return `-118,FE,90,*workID#`;
    }
    if (!mc?.panels) {
      return `-118,FE,90,*panels#`;
    }
    for (const k of Object.keys(mc.panels)) {
      for (const gitm of mc.panels[k]['comps']) {
        if (gitm.type === 'form') {
          if (XEUtils.get(gitm as any, 'config.fields', 'null') !== 'null') {
            if (!Array.isArray(gitm.config.fields)) {
              return `-118,FE,90,*fields#`;
            }
            for (const f of gitm.config.fields) {
              const keys = Object.keys(f);
              if (keys.findIndex(e => e === 'field') === -1) {
                return `-118,FE,90,*fields[i].field#`;
              }
              if (keys.findIndex(e => e === 'type') === -1) {
                return `-118,FE,90,*fields[i].type#`;
              }
            }
          }
        }
        if (gitm.type === 'table') {
          if (
            XEUtils.get(gitm as any, 'config.columns', 'null') !== 'null' &&
            !Array.isArray(gitm.config.columns)
          ) {
            return `-118,FE,90,*columns#`;
          }
        }
      }
    }
    return ``;
  }

  private parseUnitePanel(
    mc: N_oInteraction.I_unitePanel
  ): I_return<N_oInteraction.I_conf> {
    const conf: N_oInteraction.I_conf = {
      openCompName: '',
      workID: mc.workID,
      cmd: N_oInteraction.V_cmd.UNITE_PANEL,
      compBind: {},
      compConf: {}
      // eventNames: []
    };
    const result = new T_return<N_oInteraction.I_conf>();
    const errMsg = this.unitePanelParamsChk(mc);
    if (errMsg !== ``) {
      result.errmsg = errMsg;
      return result;
    }
    conf.compBind = {
      value: true, // 显示窗口
      width: mc?.style?.width ?? '600',
      height: mc?.style?.height ?? '400',
      type: 'confirm',
      mask: mc?.style?.mask ?? false,
      // 是否允许窗口边缘拖动调整窗口大小
      resize: mc?.style?.resize ?? true,
      // 标题是否标显示最大化与还原按钮
      showZoom: mc?.style?.showZoom ?? true,
      showClose: mc?.style?.showClose ?? true,
      // status: '',
      title: mc.title,
      showFooter: true,
      minWidth: mc?.style?.minWidth,
      minHeiht: mc?.style?.minHeight,
      // 是否允许按 Esc 键关闭窗口
      escClosable: mc?.style?.escClosable ?? false, // default false
      // showHeader: false,
      showTitleOverflow: true
    };

    conf.compConf = this.getUnitePanelCompConf(mc);
    conf.compConf.initValue = mc?.initValue ?? null;
    result.setReturnData('conf', conf);
    return result;
  }

  private getUnitePanelCompConf(mc: N_oInteraction.I_unitePanel): object {
    if (!libutils.noValue(mc.panels)) {
      Object.keys(mc.panels).forEach(k => {
        mc.panels[k]['comps'].forEach((el, idx) => {
          if (el.type === 'form') {
            if (XEUtils.get(el as any, 'config.fields', 'null') !== 'null') {
              // form
              this.getFormConf(
                mc.panels[k]['comps'][idx].config as N_oInteraction.I_form
              );
            }
          }
          if (el.type === 'table') {
            if (XEUtils.get(el as any, 'config.columns', 'null') !== 'null') {
              this.getTableConf(
                mc.panels[k]['comps'][idx].config as N_oInteraction.I_table
              );
            }
          }
        });
      });
    }
    return mc;
  }

  private getFormConf(form: N_oInteraction.I_form) {
    form.fields = this.getFunPanelFormColumns(form.fields);
  }

  private getTableConf(table: N_oInteraction.I_table) {
    table.columns.forEach(el => {
      el.title = el.field;
      el.slot = el.field;
      el.__id = libutils.custUUID(8, 16);
    });
  }

  private getFunPanelFormColumns(
    p: Array<N_oInteraction.I_field>
  ): Array<N_oInteraction.I_field> {
    const rFs: Array<N_oInteraction.I_field> = [];
    const fs: N_oInteraction.I_field = {
      fieldID: '',
      field: '',
      type: '',
      isShow: true,
      notNull: false,
      defValue: '',
      comment: '',
      selectionID: null,
      disabled: false,
      defaultFilter: false,
      nodeData: false,
      footerMethod: null,
      formatter: {
        type: '',
        decimal: 0,
        thousandmark: false,
        currency: ''
      },
      actions: { dochange: '' },
      auxProp: '',
      minWidth: '',
      appWeight: '',
      isDes: false,
      many2one: {
        toTable: '',
        toField: '',
        isDropdown: false,
        customSearch: '',
        multiConnect: '',
        fields: []
      },
      align: 'left',
      subQuery: ''
    };
    p.forEach(f => {
      rFs.push(XEUtils.merge(XEUtils.clone(fs, true), f));
    });
    return rFs;
  }

  private openFunParamsChk(mc: N_oInteraction.I_openFun): string {
    const chkVal: boolean = true;
    if (!mc?.workID) {
      return `-118,FE,90,*workID#`;
    }
    if (!mc?.funName) {
      return `-118,FE,90,*funName#`;
    }

    return ``;
  }

  private parseOpenFun(
    mc: N_oInteraction.I_openFun
  ): I_return<N_oInteraction.I_conf> {
    const conf: N_oInteraction.I_conf = {
      // openCompName: '',
      workID: mc.workID,
      cmd: N_oInteraction.V_cmd.OPEN_FUN,
      compBind: {},
      compConf: {}
      // eventNames: []
    };
    const result = new T_return<N_oInteraction.I_conf>();
    const errMsg = this.openFunParamsChk(mc);
    if (errMsg !== ``) {
      result.errmsg = errMsg;
      return result;
    }
    conf.compBind = {};
    // {
    //   value: true, // 显示窗口
    //   width: 800,
    //   height: 600,
    //   type: 'alert',
    //   mask: false,
    //   // 是否允许窗口边缘拖动调整窗口大小
    //   resize: true,
    //   // 标题是否标显示最大化与还原按钮
    //   showZoom: true,
    //   showClose: true,
    //   showHeader: false,
    //   showFooter: true,
    //   // fullscreen: true,
    //   minWidth: 400,
    //   minHeiht: 300
    // };
    const magicboxCf: N_oMagicbox.I_conf = {
      source: {
        field: mc.funName,
        limit: mc?.limit ?? 1,
        filter: {
          globalSearch: mc?.globalSearch,
          initSearch: mc?.filter
        }
      },
      // receiviver:
      config: {
        isFunLayout: mc?.isFunLayout === undefined ? false : mc.isFunLayout,
        customBtns: mc?.customBtns,
        hideAreas: mc?.hideList?.areas,
        tableConfig: mc?.hideList?.column,
        headTitle: mc?.headTitle
      }
    };
    conf.compConf = {
      magicboxCf,
      hideList: mc.hideList
    };
    result.setReturnData('conf', conf);
    return result;
  }

  private fieldEventParamsChk(mc: N_oInteraction.I_fieldEvent): string {
    const chkVal: boolean = true;
    // if (!mc?.updFields) {
    //   return `-118,FE,90,*updFields#`;
    // }

    return ``;
  }

  private parseFieldEvent(
    mc: N_oInteraction.I_fieldEvent
  ): I_return<N_oInteraction.I_srvCmd> {
    const conf: N_oInteraction.I_srvCmd = {
      cmd: N_oInteraction.V_cmd.FIELD_EVENT,
      updFields: mc.updFields,
      fieldsStatus: mc.fieldsStatus,
      actions: mc.actions
    };
    const result = new T_return<N_oInteraction.I_srvCmd>();
    const errMsg = this.fieldEventParamsChk(mc);
    if (errMsg !== ``) {
      result.errmsg = errMsg;
      return result;
    }
    result.setReturnData('conf', conf);
    return result;
  }

  // 新增 功能tab页签 （即：打开新功能）
  private jumpToFunParamsChk(mc: N_oInteraction.I_jumpToFun): string {
    const chkVal: boolean = true;
    // if (!mc?.updFields) {
    //   return `-118,FE,90,*updFields#`;
    // }

    return ``;
  }

  private parsejumpToFun(
    mc: N_oInteraction.I_jumpToFun
  ): I_return<N_oInteraction.I_jumpToFunConf> {
    const conf: N_oInteraction.I_jumpToFunConf = {
      cmd: N_oInteraction.V_cmd.JUMP_TO_FUN,
      funName: mc.funName, // 主功能名
      pageNo: mc.pageNo, // 跳转第几页（仅单据使用）
      actions: mc.actions
    };
    const result = new T_return<N_oInteraction.I_jumpToFunConf>();
    const errMsg = this.jumpToFunParamsChk(mc);
    if (errMsg !== ``) {
      result.errmsg = errMsg;
      return result;
    }
    result.setReturnData('conf', conf);
    return result;
  }

  //
  private handleActionsParamsChk(mc: N_oInteraction.I_executeActions): string {
    const chkVal: boolean = true;
    // if (!mc?.updFields) {
    //   return `-118,FE,90,*updFields#`;
    // }

    return ``;
  }

  //
  private searchFilterParamsChk(mc: N_oInteraction.I_searchFilter): string {
    const chkVal: boolean = true;
    // if (!mc?.updFields) {
    //   return `-118,FE,90,*updFields#`;
    // }

    return ``;
  }

  private frontendbehaviorParamsChk(
    mc: N_oInteraction.I_frontendBehavior
  ): string {
    const chkVal: boolean = true;
    // if (!mc?.updFields) {
    //   return `-118,FE,90,*updFields#`;
    // }

    return ``;
  }

  private parseHandleActions(
    mc: N_oInteraction.I_executeActions
  ): I_return<N_oInteraction.I_executeActionsConf> {
    const conf: N_oInteraction.I_executeActionsConf = {
      cmd: N_oInteraction.V_cmd.EXECUTE_ACTIONS,
      actions: mc.actions
    };
    const result = new T_return<N_oInteraction.I_executeActionsConf>();
    const errMsg = this.handleActionsParamsChk(mc);
    if (errMsg !== ``) {
      result.errmsg = errMsg;
      return result;
    }
    result.setReturnData('conf', conf);
    return result;
  }

  private parseSearchFilter(
    mc: N_oInteraction.I_searchFilter
  ): I_return<N_oInteraction.I_searchFilterConf> {
    const conf: N_oInteraction.I_searchFilterConf = {
      cmd: N_oInteraction.V_cmd.SEARCH_FILTER,
      m2oFilter: mc?.m2oFilter
    };
    const result = new T_return<N_oInteraction.I_searchFilterConf>();
    const errMsg = this.searchFilterParamsChk(mc);
    if (errMsg !== ``) {
      result.errmsg = errMsg;
      return result;
    }
    result.setReturnData('conf', conf);
    return result;
  }

  private parseFrontendBehavior(
    mc: N_oInteraction.I_frontendBehavior
  ): I_return<N_oInteraction.I_frontendBehaviorConf> {
    const conf: N_oInteraction.I_frontendBehaviorConf = {
      cmd: N_oInteraction.V_cmd.FRONTEND_BEHAVIOR,
      frontendBehavior: mc
    };
    const result = new T_return<N_oInteraction.I_frontendBehaviorConf>();
    const errMsg = this.frontendbehaviorParamsChk(mc);
    if (errMsg !== ``) {
      result.errmsg = errMsg;
      return result;
    }
    result.setReturnData('conf', conf);
    return result;
  }
}
export interface I_interaction extends T_interaction {}
